package com.jm.cloud.feign.exception;

import com.jm.framework.common.result.BaseResult;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.support.SpringDecoder;

/**
 * tide
 * <p>
 * Feign异常解码处理解码
 * <p>
 * author: jiangjianmin
 * <p>
 * create: 2024-08-22 15:13
 **/
@Slf4j
public class FeignExceptionDecoder extends ErrorDecoder.Default{
    private final SpringDecoder decoder;

    public FeignExceptionDecoder(SpringDecoder decoder) {
        this.decoder = decoder;
    }

    /**
     * 解码HTTP响应，将其转换为适当的异常
     * 首先尝试将响应解码为BaseResult对象，如果失败，则调用父类方法处理
     *
     * @param methodKey 调用的方法键
     * @param response  包含错误信息的HTTP响应
     * @return          相应的异常实例
     */
    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            BaseResult<?> result = (BaseResult<?>) decoder.decode(response, BaseResult.class);
            return new FeignException(result.getMessage());
        } catch (Exception e) {
            // 调用方异常，状态码404，405等
            return super.decode(methodKey, response);
        }
    }
}
